<!--  -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item> 
    </el-breadcrumb>
    <el-card>
        <el-row>
            <el-col>
                <el-button type="primary">添加角色</el-button>
            </el-col>
        </el-row>
        <!-- 角色列表区 -->
        <el-table :data="rolelist" border stripe>
            <el-table-column type="expand">
                <template slot-scope="scope">
                    <!-- 通过三元表达式判断顶部底部是否应该有边框线 -->
                    <el-row :class="['bdbottom', index === 0 ? 'bdtop' : '', 'vcenter' ]" v-for="(item1, index) in scope.row.children" :key="item1.id" > 
                        <!-- 渲染一级权限 -->
                        <el-col :span="5">
                            <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <!-- 渲染二级和三级权限 -->
                        <el-col :span="19">
                            <!-- 通过for循环嵌套渲染二级权限 -->
                            <el-row :class="[index2 ===0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, index2) in item1.children" :key="item2.id"  >
                                <el-col :span="7">
                                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <el-col :span="17">
                                    <el-tag v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.id)">
                                       {{item3.authName}}
                                    </el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="角色名称" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作" width="300px">
                <template slot-scope="scope" >
                    <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                    <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>

        </el-table>
    </el-card>

     <!-- 分配权限的对话框 -->
    <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="50%"
        @close="setRightDialogClosed"
    >
        <!-- 内容主题区 -->
        <!-- 树形控件 -->
        <el-tree ref="treeRef" :data="rightslist" :props="treeProps" show-checkbox node-key="id" :default-expand-all="true" :default-checked-keys="defKeys" ></el-tree>
        <!-- 底部按钮区 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="setRightDialogVisible=false">取 消</el-button>
            <el-button type="primary"  @click="updateRight">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
        //所有角色列表数据
        rolelist: [],
        //控制用户分配权限界面的显示与隐藏
        setRightDialogVisible: false,
        //所有权限的数组
        rightslist: [],
        //定义树形控件传参
        treeProps: {
            label: 'authName',
            children : 'children'
        },
        //默认选中的节点Id值为数组
        defKeys: [],
        //当前即将分配权限的角色id
        roleId: ''
    };
  },
  
  created() {
      this.getRolesList()
  },

  methods: {
         async getRolesList() {
          const{ data:res } = await this.$http.get('roles')
          if(res.meta.status !==200 ) {
             return this.$message.error('获取角色列表失败！')
          }
           
          this.rolelist = res.data
      },
      //根据id删除权限
      async removeRightById(role, rightId) {
          const confirmRes = await this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).catch(err => err)

            if(confirmRes !== 'confirm'){
                this.$message.info('取消删除')
            }else{
                const { data:res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                if(res.meta.status !==200 ){
                    return this.$message.error('删除失败，请检查网络')
                }
                role.children = res.data
                this.$message.success('删除成功！')
            }
      },
      //分配权限对话框
      async showSetRightDialog(role) {

          //保存id
          this.roleId = role.id

          //获取所有权限数据
          const { data:res } = await this.$http.get('rights/tree')
          if ( res.meta.status !== 200 ) {
              return this.$message.error('获取所有权限数据失败，请检查网络设置！')
          }

          //把获取的数据保存到rightlist数组中

          this.rightslist = res.data
          
          //递归获取三级节点的id
          this.getLeafKeys(role, this.defKeys)    

          //获取数据后再展示权限弹窗
          this.setRightDialogVisible = true
      },
      
      //通过递归函数获取三级数组的id值
      getLeafKeys(node, arr) {
          //如果当前node节点不包含children属性则为三级节点，如果不是继续递归
          if(!node.children) {
              return  arr.push(node.id)
          }
          //递归如果不满足条件继续调用主函数本身
          node.children.forEach(item => this.getLeafKeys(item, arr))

      },

      setRightDialogClosed() {
          //监听分配权限对话框的关闭事件
          this.defKeys = []
      },
      
      //点击确定分配权限
      async updateRight() {
          const keys = [
              ...this.$refs.treeRef.getCheckedKeys(),
              ...this.$refs.treeRef.getHalfCheckedKeys()
          ]

          //拿到keys用，进行拼接
          const idStr = keys.join(',')

          //发起http请求
          const { data:res } = await this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr})
          if(res.meta.status !==200 ){
              return this.$message.error('分配权限失败，请检查网络设置！')
          }
          this.$message.success('分配权限成功')
          this.getRolesList()
          this.setRightDialogVisible = false
      }

  }
}

</script>
<style lang='less' scoped>
  .el-tag {
      margin-top: 7px;
  }

  .bdtop {
      border-top: 1px solid #eee;
  }

  .bdbottom {
      border-bottom: 1px solid #eee;
  }

  .vcenter {
      display: flex;
      align-items: center;
  }
  div {
      box-sizing: border-box;
  }
</style>